// src/components/popups/adminEditPermission/EditPermission.tsx

import { useState, useEffect } from 'react';
import type { FC } from 'react';
import Select from 'react-select';
import type { EditableUser, EditPermissionProps } from '@/types/types';
import EditPermissionConfirm from '@/components/popups/adminEditPermission/EditPermissionConfirm';

const dashboardOptions = [
  { value: 'None', label: 'None' },
  { value: 'View', label: 'View' },
  { value: 'View & Edit', label: 'View & Edit' },
];
const reportOptions = [
  { value: 'None', label: 'None' },
  { value: 'View', label: 'View' },
  { value: 'View & Export', label: 'View & Export' },
];

const EditPermission: FC<EditPermissionProps> = ({ user, onClose, onSuccess }) => {
  const mapPermissionsToStates = (permissions: number[]) => {
    const has = (id: number) => permissions.includes(id);
    return {
      scholarsDashboard: has(9) ? 'None' : (has(1) && has(2) ? 'View & Edit' : (has(1) ? 'View' : 'None')),
      sponsorsDashboard: has(10) ? 'None' : (has(3) && has(4) ? 'View & Edit' : (has(3) ? 'View' : 'None')),
      scholarsReport: has(11) ? 'None' : (has(5) && has(6) ? 'View & Export' : (has(5) ? 'View' : 'None')),
      sponsorsReport: has(12) ? 'None' : (has(7) && has(8) ? 'View & Export' : (has(7) ? 'View' : 'None')),
    };
  };

  const [permissionStates, setPermissionStates] = useState({
    scholarsDashboard: 'None',
    sponsorsDashboard: 'None',
    scholarsReport: 'None',
    sponsorsReport: 'None',
  });

  const [showConfirm, setShowConfirm] = useState(false);
  const [updatedPermissions, setUpdatedPermissions] = useState<number[]>([]);
  const [updatedUser, setUpdatedUser] = useState<EditableUser>(user);

  useEffect(() => {
    const mapped = mapPermissionsToStates(user.permissions);
    setPermissionStates(mapped);
  }, [user]);

  const handleChange = (field: keyof typeof permissionStates, option: { value: string } | null) => {
    if (option) {
      setPermissionStates((prev) => ({ ...prev, [field]: option.value }));
    }
  };

  const prepareForConfirm = () => {
    const perms: number[] = [];

    // Scholars Dashboard permissions
    if (permissionStates.scholarsDashboard === 'None') {
      perms.push(9);
    } else if (permissionStates.scholarsDashboard === 'View') {
      perms.push(1);
    } else if (permissionStates.scholarsDashboard === 'View & Edit') {
      perms.push(1, 2);
    }

    // Sponsors Dashboard permissions
    if (permissionStates.sponsorsDashboard === 'None') {
      perms.push(10);
    } else if (permissionStates.sponsorsDashboard === 'View') {
      perms.push(3);
    } else if (permissionStates.sponsorsDashboard === 'View & Edit') {
      perms.push(3, 4);
    }

    // Scholars Reports permissions
    if (permissionStates.scholarsReport === 'None') {
      perms.push(11);
    } else if (permissionStates.scholarsReport === 'View') {
      perms.push(5);
    } else if (permissionStates.scholarsReport === 'View & Export') {
      perms.push(5, 6);
    }

    // Sponsors Reports permissions
    if (permissionStates.sponsorsReport === 'None') {
      perms.push(12);
    } else if (permissionStates.sponsorsReport === 'View') {
      perms.push(7);
    } else if (permissionStates.sponsorsReport === 'View & Export') {
      perms.push(7, 8);
    }

    setUpdatedPermissions(perms);
    setUpdatedUser({ ...user, permissions: perms });
    setShowConfirm(true);
  };

  return (
    <>
      <div
        className="fixed inset-0 z-[1000] flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm p-1 sm:p-6 font-poppins"
        onClick={() => {
          if (!showConfirm) onClose();
        }}
      >
        <div
          className="w-full max-w-md w-[98%] max-h-[90vh] overflow-y-auto bg-white dark:bg-slate-900 rounded-3xl shadow-2xl dark:shadow-blue-900 border border-gray-100 dark:border-slate-800 animate-fade-in-up"
          onClick={e => e.stopPropagation()}
        >
          {/* Header */}
          <div className="px-4 sm:px-8 py-4 sm:py-6 bg-white dark:bg-slate-900 flex justify-between items-center border-b border-gray-200 dark:border-slate-800 rounded-t-3xl shadow-sm">
            <h2 className="text-xl sm:text-2xl font-extrabold text-blue-700 dark:text-cyan-300 tracking-tight">Edit Permissions</h2>
            <button onClick={onClose} className="w-10 h-10 flex items-center justify-center text-gray-500 dark:text-gray-300 text-2xl font-bold rounded-full hover:bg-red-50 dark:hover:bg-red-900 hover:text-red-600 dark:hover:text-red-300 transition">
              ×
            </button>
          </div>
          {/* Content */}
          <div className="p-2 sm:p-6 space-y-5 text-xs sm:text-base text-gray-800 dark:text-gray-100">
            <div className="text-center mb-2">
              <p className="font-bold text-base sm:text-lg text-gray-900 dark:text-cyan-200">{user.firstName} {user.lastName}</p>
              <p className="text-gray-500 dark:text-gray-400 text-xs sm:text-sm">{user.email}</p>
            </div>
            {[
              { label: 'Scholars Dashboard', key: 'scholarsDashboard', options: dashboardOptions },
              { label: 'Sponsors Dashboard', key: 'sponsorsDashboard', options: dashboardOptions },
              { label: 'Scholars Reports', key: 'scholarsReport', options: reportOptions },
              { label: 'Sponsors Reports', key: 'sponsorsReport', options: reportOptions },
            ].map(({ label, key, options }) => (
              <div key={key} className="mb-2">
                <label className="block mb-1 text-xs sm:text-sm font-semibold text-blue-700 dark:text-cyan-300">{label} Access</label>
                <Select
                  options={options}
                  value={options.find((opt) => opt.value === permissionStates[key as keyof typeof permissionStates])}
                  onChange={(option) => handleChange(key as keyof typeof permissionStates, option)}
                  className="text-xs sm:text-sm"
                  styles={{
                    control: (base, state) => ({
                      ...base,
                      borderRadius: '0.75rem',
                      borderColor: state.isFocused ? '#06b6d4' : '#3B82F6',
                      minHeight: '2.5rem',
                      boxShadow: state.isFocused ? '0 0 0 2px #06b6d4' : 'none',
                      backgroundColor: state.isDisabled ? '#f3f4f6' : (document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff'),
                      color: document.documentElement.classList.contains('dark') ? '#e0f2fe' : '#1e293b',
                    }),
                    menu: (base) => ({
                      ...base,
                      borderRadius: '0.75rem',
                      backgroundColor: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                      color: document.documentElement.classList.contains('dark') ? '#e0f2fe' : '#1e293b',
                    }),
                    option: (base, state) => ({
                      ...base,
                      backgroundColor: state.isSelected
                        ? (document.documentElement.classList.contains('dark') ? '#0e7490' : '#3b82f6')
                        : state.isFocused
                          ? (document.documentElement.classList.contains('dark') ? '#334155' : '#e0f2fe')
                          : 'transparent',
                      color: state.isSelected
                        ? '#fff'
                        : (document.documentElement.classList.contains('dark') ? '#e0f2fe' : '#1e293b'),
                    }),
                    singleValue: (base) => ({
                      ...base,
                      color: document.documentElement.classList.contains('dark') ? '#e0f2fe' : '#1e293b',
                    }),
                  }}
                  classNamePrefix="react-select"
                  isSearchable={false}
                />
              </div>
            ))}
            <div className="flex flex-col sm:flex-row justify-between gap-3 pt-3">
              <button
                onClick={onClose}
                className="w-full sm:w-auto px-4 py-2 rounded-xl text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-cyan-300 border border-gray-300 dark:border-slate-700 bg-white dark:bg-slate-800 font-semibold transition"
              >
                Back
              </button>
              <button
                onClick={prepareForConfirm}
                className="w-full sm:w-auto px-4 py-2 rounded-xl text-white bg-blue-600 dark:bg-cyan-700 hover:bg-blue-700 dark:hover:bg-cyan-800 font-semibold shadow transition"
              >
                Confirm
              </button>
            </div>
          </div>
        </div>
        {showConfirm && (
          <EditPermissionConfirm
            email={user.email}
            newPermissions={updatedPermissions}
            onCancel={() => setShowConfirm(false)}
            onSuccess={() => {
              onSuccess(updatedUser);
              setShowConfirm(false);
              onClose();
            }}
          />
        )}
      </div>
    </>
  );
};

export default EditPermission;